<template>
  <div class="chat-page">
    <!-- 聊天主体内容 -->
    <div class="chat-main">
      <!-- 左侧会话列表 -->
      <div class="conversation-list">
        <div class="list-header">
          <h3>会话列表</h3>
          <div class="connection-status">
            <i :class="isConnected ? 'el-icon-success' : 'el-icon-warning'" 
               :style="{ color: isConnected ? '#67C23A' : '#E6A23C' }"></i>
            <span :style="{ color: isConnected ? '#67C23A' : '#E6A23C' }">
              {{ isConnected ? '已连接' : '连接中...' }}
            </span>
          </div>
        </div>
        <div class="conversation-items">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-conversations">
            <div class="loading-content">
              <i class="el-icon-loading loading-icon"></i>
              <p>加载会话中...</p>
            </div>
          </div>
          
          <!-- 会话列表 -->
          <div
            v-else
            v-for="conversation in conversationList"
            :key="conversation.id"
            class="conversation-item"
            :class="{ active: currentConversationId === conversation.id }"
            @click="selectConversation(conversation)"
          >
            <div class="conversation-avatar">
              <el-avatar
                :size="36"
                :src="conversation.sellerAvatar || defaultAvatar"
              />
            </div>
            <div class="conversation-info">
              <div class="conversation-title">
                {{ conversation.sellerName || "卖家" }}
              </div>
              <div class="conversation-preview">
                {{ conversation.lastMessage || "点击开始聊天" }}
              </div>
            </div>
            <div class="conversation-time">
              {{ formatTime(conversation.lastMessageTime) }}
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-if="!loading && conversationList.length === 0" class="empty-conversations">
            <div class="empty-content">
              <i class="el-icon-chat-line-round empty-icon"></i>
              <p>暂无会话</p>
              <span v-if="$route.params.productId">在商品详情页点击"联系卖家"开始聊天</span>
              <span v-else>去商品详情页联系卖家开始聊天吧</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <div v-if="currentConversation" class="chat-header">
          <div class="chat-title">
            <span class="seller-name">{{ currentConversation.sellerName || "卖家" }}</span>
            <span class="product-name">关于: {{ currentConversation.productName }}</span>
          </div>
        </div>
        <div v-else-if="!loading" class="chat-header">
          <div class="chat-title">
            <span class="seller-name">聊天中心</span>
            <span class="product-name">选择左侧会话开始聊天</span>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="message-list" ref="messageList">
          <!-- 欢迎消息 -->
          <div v-if="messageList.length === 0 && currentConversation" class="welcome-message">
            <div class="welcome-content">
              <i class="el-icon-chat-dot-round welcome-icon"></i>
              <h3>开始聊天</h3>
              <p>与卖家沟通商品详情，询问价格、成色等信息</p>
            </div>
          </div>
          
          <div
            v-for="message in messageList"
            :key="message.id"
            class="message-item"
            :class="{ 'message-mine': message.senderId === currentUserId }"
          >
            <div class="message-avatar">
              <el-avatar
                :size="28"
                :src="
                  message.senderId === currentUserId ? userAvatar : sellerAvatar
                "
              />
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div v-if="message.contentType === 'text'" class="message-text">
                  {{ message.content }}
                </div>
                <div
                  v-else-if="message.contentType === 'image'"
                  class="message-image"
                >
                  <el-image
                    :src="message.content"
                    fit="cover"
                    :preview-src-list="[message.content]"
                    class="chat-image"
                  />
                </div>
                <div v-else class="message-text">{{ message.content }}</div>
              </div>
              <div class="message-time">
                {{ formatMessageTime(message.sendAt) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="message-input">
          <div class="input-area">
            <div class="input-row">
              <el-input
                v-model="newMessage"
                type="textarea"
                :rows="2"
                :placeholder="currentConversation ? '输入消息...' : '请先选择会话'"
                @keyup.enter.native="sendMessage"
                :disabled="!currentConversation"
              />
              <div class="input-buttons">
                <el-button
                  type="text"
                  icon="el-icon-picture"
                  @click="triggerImageUpload"
                  title="发送图片"
                  :disabled="!currentConversation"
                  class="image-btn"
                />
                <el-button
                  type="primary"
                  @click="sendMessage"
                  :disabled="!newMessage.trim() || !currentConversation"
                  :loading="sending"
                  class="send-btn"
                >
                  发送
                </el-button>
              </div>
            </div>
            <input
              ref="imageInput"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleImageUpload"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "ChatPage",
  data() {
    return {
      conversationList: [],
      currentConversation: null,
      currentConversationId: null,
      messageList: [],
      newMessage: "",
      sending: false,
      defaultAvatar:
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
      selectedProduct: null,
      loading: false,
      // WebSocket相关
      stompClient: null,
      isConnected: false
    };
  },
  computed: {
    currentUserId() {
      return this.$store.state.user.userId;
    },
    userAvatar() {
      return this.$store.state.user.avatar || this.defaultAvatar;
    },
    sellerAvatar() {
      return (
        (this.currentConversation && this.currentConversation.sellerAvatar) ||
        this.defaultAvatar
      );
    }
  },
  async mounted() {
    // 先加载会话列表
    await this.loadConversationList();
    // 然后处理路由参数（只有在有参数时才处理）
    if (this.$route.params.productId) {
      this.handleRouteParams();
    }
    // 初始化WebSocket连接
    this.initWebSocket();
  },
  beforeDestroy() {
    // 组件销毁前断开WebSocket连接
    this.disconnectWebSocket();
  },
  watch: {
    currentConversationId(newVal) {
      if (newVal) {
        this.loadMessageHistory();
      }
    },
    $route(to, from) {
      // 路由变化时处理参数
      if (to.params.productId && to.params.sellerId && to.params.productName) {
        this.handleRouteParams();
      }
    }
  },
  methods: {
    // 处理路由参数
    handleRouteParams() {
      const { productId, sellerId, productName } = this.$route.params;
      // 只有在有完整路由参数时才处理
      if (productId && sellerId && productName) {
        this.selectedProduct = {
          productId: productId,
          sellerId: sellerId,
          productName: productName
        };
        // 查找或创建会话
        this.findOrCreateConversation();
      }
    },

    // 加载会话列表
    async loadConversationList() {
      this.loading = true;
      try {
        const response = await this.$axios.get("/chat/conversation/list", {
          params: {
            userId: this.currentUserId,
            page: 1,
            size: 20
          }
        });

        // 接口返回格式：{ records: [], total: 1, size: 20, current: 1 }
        if (response.data && response.data.records) {
          // 转换数据格式以匹配组件期望的结构
          this.conversationList = response.data.records.map(record => ({
            id: record.conversationId,
            productId: record.productId,
            buyerId: record.buyerId,
            sellerId: record.sellerId,
            productName: `商品${record.productId}`, // 临时名称，后续可以通过商品详情接口获取
            sellerName: "卖家",
            sellerAvatar: this.defaultAvatar,
            lastMessage: "开始聊天吧",
            lastMessageTime: record.updatedAt || record.createdAt
          }));
          
          // 为每个会话获取商品详情
          await this.loadProductDetails();
        } else {
          this.conversationList = [];
        }
      } catch (error) {
        console.error("加载会话列表失败:", error);
        this.conversationList = [];
      } finally {
        this.loading = false;
      }
    },

    // 获取商品详情
    async loadProductDetails() {
      for (let conversation of this.conversationList) {
        await this.updateConversationInfo(conversation);
      }
    },

    // 更新会话信息（获取商品详情和卖家信息）
    async updateConversationInfo(conversation) {
      try {
        const response = await this.$axios.get(`/goods/detail/${conversation.productId}`);
        if (response.data && response.data.data) {
          const goods = response.data.data;
          conversation.productName = goods.goodsName || `商品${conversation.productId}`;
          conversation.sellerName = goods.userName || "卖家";
          conversation.sellerAvatar = goods.userAvatar || this.defaultAvatar;
        }
      } catch (error) {
        console.error(`获取商品${conversation.productId}详情失败:`, error);
        // 保持默认值
      }
    },

    // 查找或创建会话
    async findOrCreateConversation() {
      // 检查是否已存在与同一卖家的会话（通过productId和sellerId双重检查）
      const existingConversation = this.conversationList.find(
        conv => conv.productId === parseInt(this.selectedProduct.productId) && 
                conv.sellerId === parseInt(this.selectedProduct.sellerId)
      );

      if (existingConversation) {
        // 如果存在会话，直接选择该会话
        this.selectConversation(existingConversation);
        //this.$message.info("已跳转到现有会话");
      } else {
        // 如果不存在，创建新会话
        await this.createNewConversation();
      }
    },

    // 创建新会话
    async createNewConversation() {
      if (!this.selectedProduct) {
        this.$message.warning("请先选择商品");
        return;
      }

      try {
        const response = await this.$axios.post("/chat/conversation/create", {
          productId: parseInt(this.selectedProduct.productId),
          buyerId: parseInt(this.currentUserId),
          sellerId: parseInt(this.selectedProduct.sellerId)
        });

        // 接口返回的是conversationId（数字）
        if (response.data && typeof response.data === 'number') {
          const conversationId = response.data;
          
          // 创建会话对象
          const newConversation = {
            id: conversationId,
            productId: parseInt(this.selectedProduct.productId),
            buyerId: parseInt(this.currentUserId),
            sellerId: parseInt(this.selectedProduct.sellerId),
            productName: this.selectedProduct.productName,
            sellerName: "卖家", // 临时名称，稍后会更新
            sellerAvatar: this.defaultAvatar,
            lastMessage: "开始聊天吧",
            lastMessageTime: new Date().toISOString()
          };
          
          // 添加到会话列表
          this.conversationList.unshift(newConversation);
          
          // 立即获取卖家信息并更新会话
          await this.updateConversationInfo(newConversation);
          
          this.selectConversation(newConversation);
          this.$message.success("会话创建成功");
        } else {
          throw new Error("创建会话失败：响应格式错误");
        }
      } catch (error) {
        console.error("创建会话失败:", error);
        this.$message.error("创建会话失败，请重试");
        // 如果接口失败，创建模拟会话
        this.createMockConversation();
      }
    },

    // 创建模拟会话
    async createMockConversation() {
      const mockConversation = {
        id: Date.now(),
        productId: parseInt(this.selectedProduct.productId),
        buyerId: parseInt(this.currentUserId),
        sellerId: parseInt(this.selectedProduct.sellerId),
        productName: this.selectedProduct.productName,
        sellerName: "卖家", // 临时名称，稍后会更新
        sellerAvatar: this.defaultAvatar,
        lastMessage: "开始聊天吧",
        lastMessageTime: new Date().toISOString()
      };

      this.conversationList.unshift(mockConversation);
      
      // 立即获取卖家信息并更新会话
      await this.updateConversationInfo(mockConversation);
      
      this.selectConversation(mockConversation);
      this.$message.success("模拟会话创建成功");
    },

    // 选择会话
    async selectConversation(conversation) {
      this.currentConversation = conversation;
      this.currentConversationId = conversation.id;

      try {
        // 调用查询单个会话详情接口
        const response = await this.$axios.get(
          `/chat/conversation/${conversation.id}`
        );
        
        // 根据接口文档，直接返回会话详情数据
        if (response.data) {
          const conversationDetail = response.data;
          // 更新当前会话信息
          this.currentConversation = { 
            ...conversation, 
            conversationId: conversationDetail.conversationId,
            productId: conversationDetail.productId,
            buyerId: conversationDetail.buyerId,
            sellerId: conversationDetail.sellerId,
            createdAt: conversationDetail.createdAt,
            updatedAt: conversationDetail.updatedAt
          };
        }
      } catch (error) {
        console.error("加载会话详情失败:", error);
        this.currentConversation = conversation;
      }

      // 更新路由参数，确保路由与实际聊天对象一致
      this.updateRouteForConversation(conversation);

      // 订阅新会话的消息
      if (this.isConnected && this.websocket) {
        this.subscribeToMessages(conversation.id);
      }
    },

    // 加载消息历史
    async loadMessageHistory() {
      if (!this.currentConversationId) return;

      try {
        const response = await this.$axios.get("/chat/history", {
          params: {
            conversationId: this.currentConversationId,
            page: 1,
            size: 50
          }
        });

        // 根据接口文档，返回格式为 { records: [], total: 1, size: 20, current: 1 }
        if (response.data && response.data.records) {
          this.messageList = response.data.records.map(message => ({
            id: message.messageId,
            conversationId: message.conversationId,
            senderId: message.senderId,
            content: message.content,
            contentType: message.contentType,
            isRead: message.isRead,
            sendAt: message.sendAt
          }));
          
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          this.messageList = [];
        }
      } catch (error) {
        console.error("加载消息历史失败:", error);
        this.messageList = [];
      }
    },

    // 发送消息
    async sendMessage() {
      if (!this.newMessage.trim() || !this.currentConversationId) return;

      this.sending = true;
      const messageContent = this.newMessage.trim();
      this.newMessage = ""; // 立即清空输入框

      try {
        const messageData = {
          conversationId: this.currentConversationId,
          senderId: parseInt(this.currentUserId),
          content: messageContent,
          contentType: "text",
          isRead: false,
          sendAt: new Date().toISOString()
        };

        // 优先使用WebSocket发送消息
        const webSocketSuccess = this.sendMessageViaWebSocket(messageData);
        
        if (webSocketSuccess) {
          // WebSocket发送成功，创建本地消息对象
          const localMessage = {
            id: Date.now(),
            conversationId: this.currentConversationId,
            senderId: parseInt(this.currentUserId),
            content: messageContent,
            contentType: "text",
            isRead: false,
            sendAt: new Date().toISOString()
          };
          
          this.messageList.push(localMessage);
          this.updateConversationLastMessage(localMessage);
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          // WebSocket发送失败，回退到HTTP接口
          console.log('WebSocket发送失败，使用HTTP接口发送');
          const response = await this.$axios.post(
            "/chat/message/send",
            messageData
          );

          // 根据接口文档，发送消息成功后返回消息对象
          if (response.data) {
            const sentMessage = response.data;
            // 确保消息对象有正确的字段
            const messageToAdd = {
              id: sentMessage.messageId || Date.now(),
              conversationId: sentMessage.conversationId,
              senderId: sentMessage.senderId,
              content: sentMessage.content,
              contentType: sentMessage.contentType,
              isRead: sentMessage.isRead,
              sendAt: sentMessage.sendAt
            };
            
            this.messageList.push(messageToAdd);
            this.updateConversationLastMessage(messageToAdd);
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          } else {
            console.error("发送失败：响应数据为空");
            // 如果HTTP也失败，创建模拟消息
            this.createMockMessage(messageContent);
          }
        }
      } catch (error) {
        console.error("发送消息失败:", error);
        // 如果所有发送方式都失败，创建模拟消息
        this.createMockMessage(messageContent);
      } finally {
        this.sending = false;
      }
    },

    // 创建模拟消息（当发送失败时）
    createMockMessage(content) {
      const mockMessage = {
        id: Date.now(),
        conversationId: this.currentConversationId,
        senderId: parseInt(this.currentUserId),
        content: content,
        contentType: "text",
        isRead: false,
        sendAt: new Date().toISOString()
      };
      this.messageList.push(mockMessage);
      this.updateConversationLastMessage(mockMessage);
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    // 更新会话的最后消息
    updateConversationLastMessage(message) {
      if (!this.currentConversation) return;
      
      // 找到当前会话在列表中的索引
      const conversationIndex = this.conversationList.findIndex(
        conv => conv.id === this.currentConversationId
      );
      
      if (conversationIndex !== -1) {
        // 更新最后消息内容
        if (message.contentType === 'text') {
          this.conversationList[conversationIndex].lastMessage = message.content;
        } else if (message.contentType === 'image') {
          this.conversationList[conversationIndex].lastMessage = '[图片]';
        } else {
          this.conversationList[conversationIndex].lastMessage = '[消息]';
        }
        
        // 更新最后消息时间
        this.conversationList[conversationIndex].lastMessageTime = message.sendAt;
        
        // 将当前会话移到列表顶部
        const currentConversation = this.conversationList.splice(conversationIndex, 1)[0];
        this.conversationList.unshift(currentConversation);
      }
    },

    // 更新路由参数以匹配当前会话
    updateRouteForConversation(conversation) {
      // 如果会话有商品信息，则使用带参数的路由
      if (conversation.productId) {
        const newRoute = {
          name: 'ChatWithProduct',
          params: {
            productId: conversation.productId.toString(),
            sellerId: conversation.sellerId.toString(),
            productName: conversation.productName || '商品'
          }
        };
        
        // 使用 replace 而不是 push，避免在历史记录中创建新条目
        this.$router.replace(newRoute);
      } else {
        // 如果会话没有商品信息，则跳转到无参数的聊天页面
        this.$router.replace({ name: 'ChatPage' });
      }
    },

    // 触发图片上传
    triggerImageUpload() {
      this.$refs.imageInput.click();
    },

    // 处理图片上传
    async handleImageUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      const isImage = file.type.startsWith("image/");
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error("只能上传图片格式!");
        return;
      }
      if (!isLt5M) {
        this.$message.error("图片大小不能超过 5MB!");
        return;
      }

      try {
        const formData = new FormData();
        formData.append("files", file);

        const response = await this.$axios.post(
          "http://localhost:8079/admin/product/multiUpload",
          formData,
          {
            headers: {
              Authorization: `Bearer ${this.$store.state.user.token}`,
              "Content-Type": "multipart/form-data"
            }
          }
        );

        if (
          response.data.code === 200 &&
          response.data.data &&
          response.data.data.length > 0
        ) {
          const imageUrl = response.data.data[0];

          const messageData = {
            conversationId: this.currentConversationId,
            senderId: parseInt(this.currentUserId),
            content: imageUrl,
            contentType: "image",
            isRead: false,
            sendAt: new Date().toISOString()
          };

          // 优先使用WebSocket发送图片消息
          const webSocketSuccess = this.sendMessageViaWebSocket(messageData);
          
          if (webSocketSuccess) {
            // WebSocket发送成功，创建本地消息对象
            const localMessage = {
              id: Date.now(),
              conversationId: this.currentConversationId,
              senderId: parseInt(this.currentUserId),
              content: imageUrl,
              contentType: "image",
              isRead: false,
              sendAt: new Date().toISOString()
            };
            
            this.messageList.push(localMessage);
            this.updateConversationLastMessage(localMessage);
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          } else {
            // WebSocket发送失败，回退到HTTP接口
            console.log('WebSocket发送图片失败，使用HTTP接口发送');
            const msgResponse = await this.$axios.post(
              "/chat/message/send",
              messageData
            );

            // 根据接口文档，发送消息成功后返回消息对象
            if (msgResponse.data) {
              const sentMessage = msgResponse.data;
              // 确保消息对象有正确的字段
              const messageToAdd = {
                id: sentMessage.messageId || Date.now(),
                conversationId: sentMessage.conversationId,
                senderId: sentMessage.senderId,
                content: sentMessage.content,
                contentType: sentMessage.contentType,
                isRead: sentMessage.isRead,
                sendAt: sentMessage.sendAt
              };
              
              this.messageList.push(messageToAdd);
              this.updateConversationLastMessage(messageToAdd);
              this.$nextTick(() => {
                this.scrollToBottom();
              });
            } else {
              // 如果接口失败，创建模拟消息
              const mockMessage = {
                id: Date.now(),
                conversationId: this.currentConversationId,
                senderId: parseInt(this.currentUserId),
                content: imageUrl,
                contentType: "image",
                isRead: false,
                sendAt: new Date().toISOString()
              };
              this.messageList.push(mockMessage);
              this.updateConversationLastMessage(mockMessage);
              this.$nextTick(() => {
                this.scrollToBottom();
              });
            }
          }
        }
      } catch (error) {
        console.error("图片上传失败:", error);
      }

      event.target.value = "";
    },

    // 滚动到底部
    scrollToBottom() {
      const messageList = this.$refs.messageList;
      if (messageList) {
        messageList.scrollTop = messageList.scrollHeight;
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return "刚刚";
      const date = new Date(time);
      const now = new Date();
      const diff = now - date;

      if (diff < 60 * 1000) {
        return "刚刚";
      } else if (diff < 60 * 60 * 1000) {
        const minutes = Math.floor(diff / (60 * 1000));
        return `${minutes}分钟前`;
      } else if (diff < 24 * 60 * 60 * 1000) {
        return date.toLocaleTimeString("zh-CN", {
          hour: "2-digit",
          minute: "2-digit"
        });
      } else {
        return date.toLocaleDateString("zh-CN");
      }
    },

    // 格式化消息时间
    formatMessageTime(time) {
      if (!time) return "";
      const date = new Date(time);
      return date.toLocaleTimeString("zh-CN", {
        hour: "2-digit",
        minute: "2-digit"
      });
    },

    // WebSocket相关方法
    // 初始化WebSocket连接
    initWebSocket() {
      try {
        // 检查全局变量是否可用
        if (typeof window.SockJS === 'undefined' || typeof window.Stomp === 'undefined') {
          console.error('WebSocket库未加载');
          this.isConnected = false;
          this.$message.warning('WebSocket库未加载，将使用HTTP模式');
          return;
        }

        // 创建SockJS连接
        const socket = new window.SockJS('http://localhost:8090/ws/chat');
        this.stompClient = window.Stomp.over(socket);
        
        // 连接WebSocket
        this.stompClient.connect({}, 
          (frame) => {
            console.log('WebSocket连接成功:', frame);
            console.log('STOMP客户端状态:', this.stompClient.connected);
            this.isConnected = true;
            //this.$message.success('WebSocket连接成功，实时聊天已启用');
            // 如果有当前会话，订阅消息
            if (this.currentConversationId) {
              this.subscribeToMessages(this.currentConversationId);
            }
          },
          (error) => {
            console.error('WebSocket连接失败:', error);
            this.isConnected = false;
            this.$message.warning('WebSocket连接失败，将使用HTTP模式进行聊天');
          }
        );
        
        // 添加连接状态监听
        this.stompClient.onStompError = (frame) => {
          console.error('STOMP错误:', frame);
          this.isConnected = false;
          this.$message.error('STOMP连接错误');
        };
        
      } catch (error) {
        console.error('初始化WebSocket失败:', error);
        this.isConnected = false;
      }
    },

    // 断开WebSocket连接
    disconnectWebSocket() {
      if (this.stompClient && this.isConnected) {
        this.stompClient.disconnect(() => {
          console.log('WebSocket连接已断开');
          this.isConnected = false;
        });
      }
    },

    // 订阅消息
    subscribeToMessages(conversationId) {
      if (!this.stompClient || !this.isConnected) {
        console.warn('WebSocket未连接，无法订阅消息');
        return;
      }

      try {
        // 订阅特定会话的消息
        this.stompClient.subscribe(`/queue/messages/${conversationId}`, (message) => {
          console.log('收到实时消息:', message);
          try {
            const receivedMessage = JSON.parse(message.body);
            
            // 将收到的消息添加到消息列表
            const messageToAdd = {
              id: receivedMessage.messageId || Date.now(),
              conversationId: receivedMessage.conversationId,
              senderId: receivedMessage.senderId,
              content: receivedMessage.content,
              contentType: receivedMessage.contentType,
              isRead: receivedMessage.isRead,
              sendAt: receivedMessage.sendAt
            };
            
            this.messageList.push(messageToAdd);
            this.updateConversationLastMessage(messageToAdd);
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          } catch (error) {
            console.error('解析WebSocket消息失败:', error);
          }
        });
        console.log('已订阅会话消息:', conversationId);
      } catch (error) {
        console.error('订阅消息失败:', error);
      }
    },

    // 通过WebSocket发送消息
    sendMessageViaWebSocket(messageData) {
      if (!this.stompClient || !this.isConnected || !this.stompClient.connected) {
        console.warn('WebSocket未连接，无法发送消息');
        return false;
      }

      try {
        // 发送消息到服务器
        this.stompClient.send('/app/chat.sendMessage', {}, JSON.stringify(messageData));
        console.log('WebSocket消息发送成功');
        return true;
      } catch (error) {
        console.error('发送WebSocket消息失败:', error);
        return false;
      }
    }
  }
};
</script>

<style scoped>
.chat-page {
  background-color: #f7f7f7;
  height: 100vh;
  padding: 10px;
  box-sizing: border-box;
}

/* 聊天主体 */
.chat-main {
  max-width: 900px;
  width: 100%;
  height: calc(100vh - 80px);
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  border: none;
  overflow: hidden;
  box-shadow: 0px 2px 10px 1px #0000002a;
  display: flex;
}

/* 左侧会话列表 */
.conversation-list {
  width: 280px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  background: white;
}

.list-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.connection-status i {
  font-size: 14px;
}

.conversation-items {
  flex: 1;
  overflow-y: auto;
  min-height: 0; /* 确保flex子元素可以收缩 */
}

.conversation-item {
  padding: 12px 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: background-color 0.3s;
}

.conversation-item:hover {
  background-color: #f5f7fa;
}

.conversation-item.active {
  background-color: #e6f7ff;
}

.conversation-avatar {
  margin-right: 12px;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-title {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}

.conversation-preview {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}

.conversation-time {
  font-size: 11px;
  color: #999;
  margin-left: 8px;
}

/* 加载状态 */
.loading-conversations {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  padding: 20px;
}

.loading-content {
  text-align: center;
  color: #999;
}

.loading-icon {
  font-size: 24px;
  color: #00caa8;
  margin-bottom: 15px;
  animation: rotate 1s linear infinite;
}

.loading-content p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 空状态 */
.empty-conversations {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  padding: 20px;
}

.empty-content {
  text-align: center;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  color: #ddd;
  margin-bottom: 15px;
}

.empty-content p {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #666;
}

.empty-content span {
  font-size: 12px;
  color: #999;
}

/* 右侧聊天区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f8f9fa;
}

.chat-title {
  font-weight: 500;
  color: #333;
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.seller-name {
  font-size: 14px;
  color: #666;
  padding: 4px 8px;
  background: #f0f0f0;
  border-radius: 12px;
}

.message-list {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
  background-color: #f5f5f5;
  min-height: 0; /* 确保flex子元素可以收缩 */
}

.message-item {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.message-item.message-mine {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 8px;
}

.message-content {
  max-width: 60%;
}

.message-bubble {
  background-color: white;
  padding: 8px 12px;
  border-radius: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  word-wrap: break-word;
}

.message-mine .message-bubble {
  background-color: #00caa8;
  color: white;
}

.message-text {
  line-height: 1.4;
  text-align: left;
}

.message-image {
  max-width: 200px;
}

.chat-image {
  width: 100%;
  border-radius: 8px;
  cursor: pointer;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  text-align: left;
}

.message-mine .message-time {
  text-align: right;
}

/* 欢迎消息 */
.welcome-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
  padding: 15px;
}

.welcome-content {
  text-align: center;
  color: #999;
}

.welcome-icon {
  font-size: 36px;
  color: #ddd;
  margin-bottom: 15px;
}

.welcome-content h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 16px;
  font-weight: 500;
}

.welcome-content p {
  margin: 0;
  color: #999;
  font-size: 13px;
  line-height: 1.4;
}

/* 消息输入区域 */
.message-input {
  border-top: 1px solid #e4e7ed;
  background-color: white;
}

.input-area {
  padding: 10px 20px;
}

.input-row {
  display: flex;
  align-items: flex-end;
  gap: 8px;
}

.input-row .el-textarea {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.input-buttons {
  display: flex;
  flex-direction: row;
  gap: 8px;
  align-items: flex-end;
}

.image-btn {
  background-color: transparent !important;
  border-color: transparent !important;
  color: #666 !important;
  padding: 8px 12px !important;
  font-size: 16px !important;
}

.image-btn:hover {
  background-color: #f5f5f5 !important;
  color: #00caa8 !important;
}

.send-btn {
  background-color: #00caa8 !important;
  border-color: #00caa8 !important;
  padding: 8px 16px !important;
  height: 32px !important;
  line-height: 1 !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-page {
    padding: 10px;
    margin-top: 60px;
    height: calc(100vh - 60px);
  }
  
  .chat-main {
    flex-direction: column;
    height: calc(100vh - 80px);
  }

  .conversation-list {
    width: 100%;
    height: 180px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }

  .chat-area {
    flex: 1;
  }
}
</style> 